import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shop/http/HttpUtil.dart';
import 'package:shop/route/my_route.dart';

import 'Login.dart';

class JifenRecords extends StatefulWidget {
  JifenRecords({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _JifenRecords createState() => _JifenRecords();
}

class _JifenRecords extends State<JifenRecords> {
  List<Widget> items = [Text("1"), Text("2"),Text("3"),Text("4"),Text("5"),Text("6")];
  List liushuis=[];
  int page=1;

  // 上拉加载控制器
  RefreshController _refreshController = RefreshController(initialRefresh: false);

  // 构造函数
  _JifenRecords(){
    isLogin();
  }

  // 判断是否登录
  Future<void> isLogin() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if(prefs.getBool("isLogin")==false){
      Fluttertoast.showToast(
          msg: "请先登录"
      );
      MyRoute.replace(Login());
    }else{
      _onLoading();
    }
  }
  // 刷新时调用
  void _onRefresh() async{
    // monitor network fetch
    // await Future.delayed(Duration(milliseconds: 1000));
    // if failed,use refreshFailed()
    _refreshController.refreshCompleted();
  }
  // 加载数据的函数
  void _onLoading() async{
    // monitor network fetch
    // await Future.delayed(Duration(milliseconds: 1000));
    // Response response = await Dio().get("http://xllm.szghrj.com:8082/app/goods/searchAllGoods?limit=10&page=${page}");
    // var x = json.decode(response.toString());
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String userId = prefs.getString("userId");
    var y = await HttpUtil().get("/app/liushui/searchUserLiushui?userId="+userId+"&page=${page}"+"&limit=10");
    page++;
    if(y['code']==200){
      liushuis.addAll(y['data']);
      if(y['data'].length<1){
        _refreshController.loadNoData();
        return;
      }
    }
    // if failed,use loadFailed(),if no data return,use LoadNodata()
    if(mounted){
      setState(() {});
      _refreshController.loadComplete();
    }
  }

  // 显示积分记录
  GestureDetector _showGoods(item){
    return GestureDetector(
      child: Container(
                  padding: EdgeInsets.fromLTRB(10, 10, 0, 0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(item['money'].toString()+"积分",style: TextStyle(color: Colors.orange,fontSize: 20),),
                          Text(item['createTime']),
                        ],
                      ),
                      SizedBox(height: 10,),
                      Expanded(child: Text(item['message']))
                      // Row(children: [Text(item['message'])],),
                    ],
                  ),
              )
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("消费记录"),
      ),
      body: SmartRefresher(
        enablePullDown: false,
        enablePullUp: true,
        header: WaterDropHeader(),
        footer: CustomFooter(
          builder: (BuildContext context,LoadStatus mode){
            Widget body ;
            if(mode==LoadStatus.idle){
              body =  Text("上拉加载");
            }
            else if(mode==LoadStatus.loading){
              body =  CupertinoActivityIndicator();
            }
            else if(mode == LoadStatus.failed){
              body = Text("加载失败！点击重试！");
            }
            else if(mode == LoadStatus.canLoading){
              body = Text("松手,加载更多!");
            }
            else{
              body = Text("没有更多数据了!");
            }
            return Container(
              height: 55.0,
              child: Center(child:body),
            );
          },
        ),
        controller: _refreshController,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.builder(
          itemBuilder: (c, i) => Card(child: _showGoods(liushuis[i])),
          itemExtent: 100.0,
          itemCount: liushuis.length,
        ),
      ),
    );
  }
}